#include <arpa/inet.h>
#include <atomic>
#include <ctime>
#include <stdio.h>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdexcept>

std::atomic<bool> g_running{false};

void handleSignal(int signo) { throw std::runtime_error((char *)"程序退出"); }

std::string getTime() {
    time_t now = time(0);
    char currentTime[80];
    strftime(currentTime, sizeof(currentTime), "%Y-%m-%d %H:%M:%S",
             localtime(&now));
    return std::string(currentTime);
}

int main(int argv, char **argc) {
    signal(SIGINT, handleSignal);

    int fp = socket(AF_INET, SOCK_STREAM, 0);
    if (fp < 0) {
        printf("套接字创建失败.\n");
        return -1;
    }

    struct sockaddr_in addr;
    char *ip = (char *)("10.50.34.149");
    int port = 8088;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(port);
    if (connect(fp, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
        printf("服务器连接失败. ip: %s port: %d\n", ip, port);
        return -1;
    }

    printf("连接服务器成功，ip: %s, port: %d, 开始发送数据\n", ip, port);

    g_running.store(true);
    int pid = getpid();
    try {
        while (g_running.load()) {
            const std::string msg = "Hello, I'm client#" + std::to_string(pid) +
                                    ". Send time is " + getTime() + "\n";
            printf("发送数据：%s\n", msg.c_str());
            if (send(fp, msg.c_str(), msg.size(), 0) == -1) {
                printf("发送数据失败\n");
            }
            sleep(3);
        }
    } catch (const std::exception &e) {
        printf("客服端接受到一个异常(%s)，开始关闭服务器.\n", e.what());
    }
    g_running.store(false);
    printf("退出客户端\n");
    close(fp);

    return 0;
}
